package com.oddpointcc.szpt.accounting.component;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Aspect
@Component
public class LogAspect {
	private static final Logger LOG = LogManager.getLogger(LogAspect.class);

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private ObjectMapper objectMapper;

	@Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.GetMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)")
	public void controllerAspect() {
	}

	@Before("controllerAspect()")
	public void doBefore(JoinPoint joinPoint) {
		HttpSession session = request.getSession();
		String username = (String) session.getAttribute("userUsername");
		String remoteAddr = request.getRemoteAddr();// 请求的IP
		String requestUri = request.getRequestURI();// 请求的Uri
		String method = request.getMethod(); // 请求的方法类型(post/get)
		String methodName = joinPoint.getSignature().getName();
		Map<String, String[]> params = request.getParameterMap(); // 请求提交的参数
		String paramJson = null;
		try {
			paramJson = objectMapper.writeValueAsString(params);
		} catch (JsonProcessingException e) {
		}
		LOG.info("username:{} remoteAddr:{} requestUri:{} method:{} methodName:{} params:{}", username, remoteAddr,
				requestUri, method, methodName, paramJson);
	}

}